package au.com.bluelink.scjp.chap7;

import java.util.*;

public class GenericsTest {

	public static void main(String[] args) {

		// WARNINGS GENERATED ON THE METHODS SIGNATURE AND THE ITERATOR
		TestLegacy.test();
		
		
		// NOTE THE COMPILER WARNINGS PRODUCED IN THE BELOW METHODS
		// THAT INDICATE THAT WE SHOULD BE USING GENERICS

		// passing a generic method into a legacy / non-generic method
		// the method adds a correct element type but the compiler can't check
		TestBadLegacy.test();

		// same as above but the insert(...) method adds an incorrect type
		// something bad might happen at runtime!!
		TestBadLegacy2.test();

	}

}


class TestLegacy {
	public static void test() {
		List<Integer> myList = new ArrayList<Integer>();
		// type safe collection
		myList.add(4);
		myList.add(6);
		Adder adder = new Adder();
		int total = adder.addAll(myList);
		// pass it to an untyped argument
		System.out.println(total);
	}
}


class Adder {
	int addAll(List list) {
		// method with a non-generic List argument,
		// but assumes (with no guarantee) that it will be Integers
		Iterator it = list.iterator();
		int total = 0;
		while (it.hasNext()) {
			int i = ((Integer) it.next()).intValue();
			total += i;
		}
		return total;
	}
}


class TestBadLegacy {
	public static void test() {
		List<Integer> myList = new ArrayList<Integer>();
		myList.add(4);
		myList.add(6);
		Inserter in = new Inserter();
		in.insert(myList); // pass List<Integer> to legacy code
	}
}


// simulating a class that we can't access (i.e. legacy API code)
class Inserter {
	// method with a non-generic List argument
	void insert(List list) {
		list.add(new Integer(42)); // adds to the incoming list
	}
}


class TestBadLegacy2 {
	public static void test() {
		List<Integer> myList = new ArrayList<Integer>();
		myList.add(4);
		myList.add(6);
		Inserter2 in = new Inserter2();
		in.insert(myList); // pass List<Integer> to legacy code
	}
}


// simulating a class that we can't access (i.e. legacy API code)
class Inserter2 {
	// method with a non-generic List argument
	void insert(List list) {
		list.add(new String("42")); // put a String in the list
		// passed in
	}
}